package com.example.studentmanagement2.service.Impl;

import com.example.studentmanagement2.model.Course;
import com.example.studentmanagement2.repository.Repository.CourseRepository;
import com.example.studentmanagement2.service.CourseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class CourseServiceImpl implements CourseService {
    private final CourseRepository courseRepository;

    public CourseServiceImpl(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    @Override
    public List<Course> getAllCourses() {
        return courseRepository.findAll();
    }

    @Override
    public Optional<Course> getCourseById(String courseId) {
        return courseRepository.findById(courseId);
    }

    @Override
    public Course addCourse(Course course) {
        if (courseRepository.findById(course.getCourseId()).isPresent()) {
            throw new IllegalArgumentException("课程编号已存在！");
        }
        return courseRepository.save(course);
    }

   // CourseServiceImpl.java
   @Override
   @Transactional
   public Course updateCourse(String originalCourseId, Course updatedCourse) {
       // 检查原始课程是否存在
       if (!courseRepository.existsById(originalCourseId)) {
           throw new IllegalArgumentException("原课程不存在");
       }

       // 检查新课程编号是否已被占用（排除自身）
       if (!originalCourseId.equals(updatedCourse.getCourseId())
               && courseRepository.existsById(updatedCourse.getCourseId())) {
           throw new IllegalArgumentException("新课程编号已存在");
       }

       // 执行更新
       courseRepository.update(originalCourseId, updatedCourse);
       return updatedCourse;
   }

    @Override
    public void deleteCourse(String courseId) {
        courseRepository.deleteById(courseId);
    }
    @Override
    public List<Course> searchCourses(String keyword) {
        return courseRepository.search(keyword);
    }
}